#include <iostream>
#include <vector>
#include <semaphore.h>
#include <pthread.h>

using namespace std;

template<class T>
class RingQueue
{
private:
    void P(sem_t& sem)
    {
        sem_wait(&sem);
    }
    void V(sem_t& sem)
    {
        sem_post(&sem);
    }
    void Lock(pthread_mutex_t& mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void Unlock(pthread_mutex_t& mutex)
    {
        pthread_mutex_unlock(&mutex);
    }
public:
    RingQueue(int max = 5)
        :_v(max), _max(max), _c_index(0), _p_index(0)
    {
        sem_init(&_c_sem, 0, 0);
        sem_init(&_p_sem, 0, max);
        pthread_mutex_init(&_c_mutex, nullptr);
        pthread_mutex_init(&_p_mutex, nullptr);
    }

    void Push(const T& in)
    {
        P(_p_sem);
        Lock(_p_mutex);
        _v[_p_index] = in;
        _p_index++;
        _p_index %= _max;
        Unlock(_p_mutex);
        V(_c_sem);
    }

    void Pop(T* out)
    {
        P(_c_sem);
        Lock(_c_mutex);
        *out = _v[_c_index];
        _c_index++;
        _c_index %= _max;
        Unlock(_c_mutex);
        V(_p_sem);
    }

    ~RingQueue()
    {
        sem_destroy(&_c_sem);
        sem_destroy(&_p_sem);
        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }
private:
    vector<T> _v;
    int _max;

    int _c_index;
    int _p_index;

    sem_t _c_sem;
    sem_t _p_sem;

    pthread_mutex_t _c_mutex;
    pthread_mutex_t _p_mutex;
};